{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 描述\n",
    "Python条件语句是通过一条或多条语句的执行结果（True或者False）来决定执行的代码块。\n",
    "\n",
    "\n",
    "# 语法\n",
    "Python程序语言指定任何非0和非空（null）值为true，0 或者 null为false。\n",
    "\n",
    "Python 编程中 if 语句用于控制程序的执行，基本形式为：\n",
    "\n",
    "```\n",
    "if 判断条件：\n",
    "    执行语句……\n",
    "else：\n",
    "    执行语句……\n",
    "```\n",
    "\n",
    "\n",
    "# 流程图\n",
    "\n",
    "可以通过下图来简单了解条件语句的执行过程:\n",
    "\n",
    "![if-条件语句](https://pptwinpics.oss-cn-beijing.aliyuncs.com/if-condition_20191126151646.jpg)\n",
    "\n",
    "其中\"判断条件\"成立时（非零），则执行后面的语句，而执行内容可以多行，以缩进来区分表示同一范围。\n",
    "\n",
    "else 为可选语句，当需要在条件不成立时执行内容则可以执行相关语句。\n",
    "\n",
    "Gif 演示：\n",
    "![if-条件语句-动画演示](https://pptwinpics.oss-cn-beijing.aliyuncs.com/if-%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5-%E5%8A%A8%E7%94%BB%E6%BC%94%E7%A4%BA_20191126151843.gif)\n",
    "\n",
    "# 实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "luren\n"
     ]
    }
   ],
   "source": [
    "# 例1：if 基本用法\n",
    " \n",
    "flag = False\n",
    "name = 'luren'\n",
    "if name == 'python':         # 判断变量是否为 python \n",
    "    flag = True              # 条件成立时设置标志为真\n",
    "    print('welcome boss')     # 并输出欢迎信息\n",
    "else:\n",
    "    print(name)               # 条件不成立时输出变量名称"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "if 语句的判断条件可以用>（大于）、<(小于)、==（等于）、>=（大于等于）、<=（小于等于）来表示其关系。\n",
    "\n",
    "当判断条件为多个值时，可以使用以下形式：\n",
    "\n",
    "```\n",
    "if 判断条件1:\n",
    "    执行语句1……\n",
    "elif 判断条件2:\n",
    "    执行语句2……\n",
    "elif 判断条件3:\n",
    "    执行语句3……\n",
    "else:\n",
    "    执行语句4……\n",
    "```\n",
    "\n",
    "# 实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "roadman\n"
     ]
    }
   ],
   "source": [
    "# 例2：elif用法\n",
    "\n",
    "num = 5     \n",
    "if num == 3:            # 判断num的值\n",
    "    print('boss')        \n",
    "elif num == 2:\n",
    "    print('user')\n",
    "elif num == 1:\n",
    "    print('worker')\n",
    "elif num < 0:           # 值小于零时输出\n",
    "    print('error')\n",
    "else:\n",
    "    print('roadman')     # 条件均不成立时输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于 python 并不支持 switch 语句，所以多个条件判断，只能用 elif 来实现，如果判断需要多个条件需同时判断时，可以使用 or （或），表示两个条件有一个成立时判断条件成功；使用 and （与）时，表示只有两个条件同时成立的情况下，判断条件才成功。\n",
    "\n",
    "# 实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello\n",
      "undefine\n",
      "undefine\n"
     ]
    }
   ],
   "source": [
    "# 例3：if语句多个条件\n",
    " \n",
    "num = 9\n",
    "if num >= 0 and num <= 10:    # 判断值是否在0~10之间\n",
    "    print('hello')\n",
    "# 输出结果: hello\n",
    " \n",
    "num = 10\n",
    "if num < 0 or num > 10:    # 判断值是否在小于0或大于10\n",
    "    print('hello')\n",
    "else:\n",
    "    print('undefine')\n",
    "# 输出结果: undefine\n",
    " \n",
    "num = 8\n",
    "# 判断值是否在0~5或者10~15之间\n",
    "if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    \n",
    "    print('hello')\n",
    "else:\n",
    "    print('undefine')\n",
    "# 输出结果: undefine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当if有多个条件时可使用括号来区分判断的先后顺序，括号中的判断优先执行，此外 and 和 or 的优先级低于>（大于）、<（小于）等判断符号，即大于和小于在没有括号的情况下会比与或要优先判断。\n",
    "\n",
    "# 简单的语句组\n",
    "你也可以在同一行的位置上使用if条件判断语句，如下实例：\n",
    "\n",
    "# 实例"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "变量 var 的值为100\n",
      "Good bye!\n"
     ]
    }
   ],
   "source": [
    "var = 100 \n",
    " \n",
    "if ( var  == 100 ) : print(\"变量 var 的值为100\" )\n",
    " \n",
    "print(\"Good bye!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 其他实例\n",
    "python 复合布尔表达式计算采用短路规则，即如果通过前面的部分已经计算出整个表达式的值，则后面的部分不再计算。如下面的代码将正常执行不会报除零错误："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "no\n"
     ]
    }
   ],
   "source": [
    "a=0\n",
    "b=1\n",
    "if ( a > 0 ) and ( b / a > 2 ):\n",
    "    print(\"yes\")\n",
    "else :\n",
    "    print(\"no\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "而下面的代码就会报错："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "ename": "ZeroDivisionError",
     "evalue": "division by zero",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mZeroDivisionError\u001b[0m                         Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-8-8d603adea5df>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0ma\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mb\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0;34m(\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m0\u001b[0m \u001b[0;34m)\u001b[0m \u001b[0;32mor\u001b[0m \u001b[0;34m(\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0ma\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m2\u001b[0m \u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      4\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"yes\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m \u001b[0;32melse\u001b[0m \u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
     ]
    }
   ],
   "source": [
    "a=0\n",
    "b=1\n",
    "if ( a > 0 ) or ( b / a > 2 ):\n",
    "    print(\"yes\")\n",
    "else :\n",
    "    print(\"no\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个简单的条件循环语句实现汉诺塔问题\n",
    "更多汉诺塔问题参阅：https://www.runoob.com/w3cnote/python-tower.html"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "('a', '-->', 'c')\n",
      "('a', '-->', 'b')\n",
      "('c', '-->', 'b')\n",
      "('a', '-->', 'c')\n",
      "('b', '-->', 'a')\n",
      "('b', '-->', 'c')\n",
      "('a', '-->', 'c')\n"
     ]
    }
   ],
   "source": [
    "def my_print(args):\n",
    "    print(args)\n",
    "\n",
    "def move(n, a, b, c):\n",
    "    my_print ((a, '-->', c)) if n==1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))\n",
    "\n",
    "move (3, 'a', 'b', 'c')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python 没有 switch/case 语句，如果遇到很多中情况的时候，写很多的 if/else 不是很好维护，这时可以考虑用字典映射的方法替代："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "zero\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "def zero():\n",
    "    return \"zero\"\n",
    "\n",
    "def one():\n",
    "    return \"one\"\n",
    "\n",
    "def two():\n",
    "    return \"two\"\n",
    "\n",
    "def num2Str(arg):\n",
    "    switcher={\n",
    "        0:zero,\n",
    "        1:one,\n",
    "        2:two,\n",
    "        3:lambda:\"three\"\n",
    "    }\n",
    "    func=switcher.get(arg,lambda:\"nothing\")\n",
    "    return func()\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    print(num2Str(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "if 简单条件判断一行搞定："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3]\n",
      "c 是一个空列表\n"
     ]
    }
   ],
   "source": [
    "a = [1,2,3]\n",
    "b = a if len(a) != 0 else \"\"\n",
    "print(b)\n",
    "\n",
    "c=[]\n",
    "d = c if len(c) != 0 else \"c 是一个空列表\"\n",
    "print(d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "将列表中重复的数据放在后面，返回列表中元素去除重复后的个数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "def deduplication(nums):\n",
    "    # write your code here\n",
    "    exist_nums = {} \n",
    "    pointer = 0\n",
    "    for num in nums:\n",
    "        if num not in exist_nums:\n",
    "            exist_nums[num] = True\n",
    "            nums[pointer] = num\n",
    "            pointer += 1\n",
    "    return pointer\n",
    "print(deduplication([1,1,1,1,1,1,2,2,2,2,2,2,2,2]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
